package org.ttitfly.zuoyue.service.attachment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.ttitfly.zuoyue.dao.attachment.AttachmentDao;
import org.ttitfly.zuoyue.entity.attachment.Attachment;

@Component
public class AttachmentManager {
	
	private static final int BUFFER_SIZE = 4 * 1024;
	
	private String uploadDir = "C:/upload/";
	
	public void setUploadDir(String uploadDir) {
		this.uploadDir = uploadDir;
	}
	
	@Resource
	private AttachmentDao attachmentDao;

	public Attachment upload(Attachment attachment) throws IOException {
		if (attachment == null || attachment.getFile() == null) {
			throw new IllegalArgumentException("argument file can not be null!");
		}
		
		try {
		InputStream in = new FileInputStream(attachment.getFile());
		File destFile = new File(uploadDir + attachment.getPath());
		if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }
		OutputStream out = new FileOutputStream(destFile);
		byte[] buf = new byte[BUFFER_SIZE];
		for (int read = in.read(buf, 0, BUFFER_SIZE); read != -1; read = in.read(buf, 0, BUFFER_SIZE)) {
			out.write(buf, 0, read);
		}
		attachmentDao.save(attachment);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return attachment;
	}
	
	/**
	 * 获取下载的文件
	 * 
	 * @param id
	 * @return
	 */
	public Attachment get(Long id) {
		return attachmentDao.get(id);
	}
	
	/**
	 * 获取下载的文件
	 * 
	 * @param id
	 * @return
	 * @throws IOException 
	 */
	public Attachment download(Long id) throws IOException {
		Attachment attachment = get(id);
		attachment.setFile(new File(uploadDir + attachment.getPath()));
		return attachment;
	}

	public void remove(Long id) {
		Attachment attachment = attachmentDao.get(id);
		attachmentDao.delete(attachment);
		File file = new File(uploadDir + attachment.getPath());
		if (file.exists() && file.isFile()) {
			file.delete();
		}
	}
}
